import models from '../../../models'

export default defineEventHandler(async (event: any) => {
  try {
    const id = parseInt(event.context.params.id)
    const body = await readBody(event)
    const { name, code, level, parentCode } = body

    // 验证代码长度
    if (![4, 6, 9, 12].includes(code.length)) {
      throw createError({
        statusCode: 400,
        message: '地区代码长度不正确'
      })
    }

    // 验证上级代码
    if (parentCode) {
      const parent = await models.Region.findOne({
        where: { code: parentCode }
      })
      
      if (!parent) {
        throw createError({
          statusCode: 400,
          message: '上级地区不存在'
        })
      }

      // 验证代码前缀
      if (!code.startsWith(parentCode)) {
        throw createError({
          statusCode: 400,
          message: '地区代码必须以上级代码为前缀'
        })
      }
    }
    
    const [updatedCount, [region]] = await models.Region.update({
      name,
      code,
      level,
      parentCode
    }, {
      where: { id },
      returning: true
    })
    
    if (updatedCount === 0) {
      throw createError({
        statusCode: 404,
        message: '地区不存在'
      })
    }
    
    return {
      success: true,
      region
    }
  } catch (error:any) {
    if (error.name === 'SequelizeUniqueConstraintError') {
      throw createError({
        statusCode: 400,
        message: '地区代码已存在'
      })
    }
    throw error
  }
}) 